"""
多任务tcp服务器
"""

import socket
import threading


# 多任务的功能函数
def client_task(client_socket, ip_port):
    print(ip_port, '连接上来了...')
    # 持续接收客户的消息
    while True:
        data = client_socket.recv(1024).decode('gbk')
        if len(data) != 0:
            print('客户端', ip_port[0], '发来的消息是: ', data)

        else:
            print('客户端', ip_port[0], '已断开连接,下次再见...')
            break

            # 服务端回复的消息
        send_data = ('Hello Socket --- ' + data).encode('gbk')
        client_socket.send(send_data)


if __name__ == '__main__':
    # 创建socket服务器对象
    server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    # 端口复用
    server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, True)
    # 绑定IP,不写地址默认本机地址
    server_socket.bind(('192.168.16.105', 7777))
    # 设置监听
    server_socket.listen(128)
    # 循环接收客户连接
    while True:
        client_socket, ip_port = server_socket.accept()
        # 实现多任务
        t_client = threading.Thread(target=client_task, args=(client_socket, ip_port))
        # 设置守护线程
        t_client.setDaemon(True)
        # 启动多任务
        t_client.start()

    server_socket.close()
